package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpLogMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogService empLogService;

    //-----------------------------------------------原始分页查询-----------------------------------------------------

    /*@Override
    public PageResult<Emp> page(Integer page, Integer pageSize) {
        //1.调用Mapper接口，查询总记录数
        Long total = empMapper.count();

        //2.调用Mapper接口，查询结果列表
        Integer start = (page - 1) * pageSize;
        List<Emp> rows = empMapper.list(start, pageSize);

        //3.封装结果 PageResult
        return new PageResult<Emp>(total,rows);
        }
        */

    //-----------------------------------------------PageHelper分页查询-----------------------------------------------------

    /*@Override
    public PageResult<Emp> page(Integer page, Integer pageSize, String name, Integer gender, LocalDate begin, LocalDate end) {
        //1.设置分页参数(PageHelper)
        PageHelper.startPage(page,pageSize);
        //2.执行查询
        List<Emp> empList = empMapper.list(name,gender,begin,end);
        //3.解析查询结果并封装
        Page<Emp> p = (Page<Emp>) empList;
        return new PageResult<>(p.getTotal(),p.getResult());*/

    @Override
    public PageResult<Emp> page(EmpQueryParam empQueryParam) {
        //1.设置分页参数(PageHelper)
        PageHelper.startPage(empQueryParam.getPage(), empQueryParam.getPageSize());
        //2.执行查询
        List<Emp> empList = empMapper.list(empQueryParam.getName(), empQueryParam.getGender(), empQueryParam.getBegin(), empQueryParam.getEnd());
        //3.解析查询结果并封装
        Page<Emp> p = (Page<Emp>) empList;
        return new PageResult<>(p.getTotal(), p.getResult());
    }

    //新增员工
    @Transactional(rollbackFor = {Exception.class}) //Spring事务-默认出现运行时异常RuntimeException才会回滚
    @Override
    public void save(Emp emp) {
        try {
            //1.保存员工的基本信息
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.insert(emp);

            //2.保存员工的工作经历信息
            List<EmpExpr> exprList = emp.getExprList();
            if (!CollectionUtils.isEmpty(exprList)) {
                for (EmpExpr empExpr : exprList) {
                    empExpr.setEmpId(emp.getId());
                }
                empExprMapper.insertBatch(exprList);
            }
        } finally {
            //3.记录操作日志
            EmpLog empLog = new EmpLog(null, LocalDateTime.now(), "新增员工:" + emp);
            empLogService.insertLog(empLog);
        }
    }

    //删除员工
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public void delete(List<Integer> ids) {
        //1.批量删除员工基本信息
        empMapper.deleteByIds(ids);
        //2.批量删除员工的工作经历
        empExprMapper.deletByEmpIds(ids);
    }

    //查询回显
    @Override
    public Emp getInfo(Integer id) {
        return empMapper.getById(id);
    }

    //修改员工
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Emp emp) {
        //1.根据ID修改员工的基本信息
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateById(emp);
        //2.根据ID修改员工的工作经历信息
        //2.1根据员工的ID删除原有的工作经历-复用上面的删除员工的方法
        empExprMapper.deletByEmpIds(Arrays.asList(emp.getId()));
        //2.2添加新的工作经历
        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)){
            for (EmpExpr empExpr : exprList) {
                empExpr.setId(emp.getId());
                empExprMapper.insertBatch(exprList);
            }
        }
    }

    //查询全部员工
    @Override
    public List<Emp> getAllEmp() {
        return empMapper.getAllEmp();
    }

    //员工登录
    @Override
    public LoginInfo login(Emp emp) {
        //1.调用Mapper接口，根据用户名和密码查询员工信息
        Emp e = empMapper.selectByUsernameAndPassword(emp);
        //2.判断是否存在这个员工，存在，组装登录成功信息
        if (e != null){
            log.info("登录成功，员工信息为：{}",e);

            //生成JWT令牌
            Map<String, Object> Claims = new HashMap<>();
            Claims.put("id",e.getId());
            Claims.put("username",e.getUsername());
            String jwt = JwtUtils.generateToken(Claims);

            return new LoginInfo(e.getId(),e.getUsername(),e.getName(),jwt);
        }
        //3.不存在，返回null
        return null;
    }
}
